package com.feinno.urcs.group.siputils;

import com.feinno.sip.address.AddressImpl;
import com.feinno.sip.address.GenericURI;
import com.feinno.sip.address.SipUri;
import com.feinno.sip.header.*;
import com.feinno.sip.header.extensions.AcceptContact;
import com.feinno.sip.header.ims.PAssertedIdentity;
import com.feinno.urcs.content.ResourceLists;
import com.feinno.urcs.content.UrcsMultipartMimeContent;
import com.feinno.urcs.group.GroupConfiguration;
import com.feinno.urcs.group.GroupConstants;
import com.feinno.urcs.group.GroupError;
import com.feinno.urcs.group.GroupException;
import com.feinno.urcs.nai.IMPU;
import com.feinno.urcs.sipservlet.SipServletRequest;
import com.feinno.urcs.types.MobileNo;

import javax.sip.address.Address;
import javax.sip.address.SipURI;
import javax.sip.address.TelURI;
import javax.sip.address.URI;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

/**
 * 群的一些基础信息验证.
 *
 * @author Li.Hongbo <lihongbo@feinno.com>
 */
public class GroupHeaderUtils {
	/**
	 * 验证是否中国移动定制终端.
	 * 协议规定中国移动定制终端需要携带:+g.3gpp.iari-ref="urn%3Aurn-7%3A3gpp-application.ims.iari.rcs.mnc000.mcc460.gpmanage;vs=1"
	 *
	 * @return
	 */
//	@Deprecated
//	public static boolean isCMCustomized(String customizedContact) {
//		return isContainsGPManager(customizedContact);
//	}
	public static boolean isContainsGPManager(SipServletRequest request) {
		boolean result = false;

		if (request != null) {
			AcceptContact acceptContact = (AcceptContact) request.getHeader(AcceptContact.NAME);
			// 获取 AcceptContact 头
			if (acceptContact != null) {
				result = isContainsGPManager(acceptContact.getParameter(GroupConstants.G_3GPP_IARI_REF));
			}

		}
		return result;
	}

	public static boolean isContainsGPManager(String acceptContactTag) {
		return acceptContactTag != null ? GroupConstants.G_3GPP_GPMANAGER.equals(acceptContactTag) : false;
	}


	/**
	 * 判断是否携带列表( 通过require 头内容为recipient-list-invite 判定.
	 * 若头不存在或者内容不为recipient-list-invite 则认为不携带列表
	 *
	 * @param requireHeader
	 * @return
	 */
	public static boolean hasRequireList(Require requireHeader) {
		return (requireHeader != null && requireHeader.getValue() != null) ? GroupConstants.RECIPIENT_LIST_INVITE.equals(requireHeader.getValue()) : false;

	}


	public static boolean isCreateGroup(String requestUri) {
		return requestUri != null ? GroupConfiguration.INSTANCE.getRcseConferenceUri().equals(requestUri) : false;

	}

	public static String getFromUriStr(SipServletRequest sipServletRequest) {
		URI uri = getFromUri(sipServletRequest);
		if (uri != null) return uri.toString();
		return null;
	}

	public static URI getFromUri(SipServletRequest sipServletRequest) {
		if (sipServletRequest != null) {
			From from = (From) sipServletRequest.getHeader(From.NAME);
			if (from != null) {
				return from.getAddress().getURI();
			}
		}
		return null;
	}

	public static URI getFromUriByPAssertedIdentity(SipServletRequest sipServletRequest) {
		if (sipServletRequest != null) {
			PAssertedIdentity paiHeader = (PAssertedIdentity) sipServletRequest.getHeader(PAssertedIdentity.NAME);
			if (paiHeader != null) return paiHeader.getAddress().getURI();
		}
		return null;
	}


	public static int parseGroupId(SipServletRequest request) throws GroupException {
		if (!request.getRequestURI().isSipURI()) {
			throw new GroupException(GroupError.NO_DESTINATIONS, "BadUri:" + request.getRequestURI().toString(), null);
		}
		int groupId = getGroupIdFromUri(request.getRequestURI().toString());
		return groupId;
	}


	public static String getRequestUriStr(SipServletRequest sipServletRequest) {
		if (sipServletRequest != null) {
			return sipServletRequest.getRequestURI().toString();
		}
		return null;
	}

	public static Contact createContactHeader(String uri, boolean has_g3gppicsiref, boolean isFocus) throws ParseException {
		Contact contactHeader = new Contact();
		GenericURI groupGenericURI = new GenericURI(uri);
		Address groupAddress = new AddressImpl();
		groupAddress.setURI(groupGenericURI);
		contactHeader.setAddress(groupAddress);

		if (has_g3gppicsiref)
			contactHeader.setParameter(GroupConstants.G_3GPP_IARI_REF, GroupConstants.G_3GPP_ICSI_REF_SESSION_VALUE);
		if (isFocus)
			contactHeader.addIsFocus();

		return contactHeader;
	}

//	public static PAssertedIdentity getPAssertedIdentity(String uri) throws ParseException {
//		PAssertedIdentity paid = new PAssertedIdentity();
//		Address tmpPai = new AddressImpl();
//		GenericURI groupGenericURI = new GenericURI(uri);
//		tmpPai.setURI(groupGenericURI);
//		paid.setAddress(tmpPai);
//		return paid;
//	}


	public static String getConversationID(SipServletRequest request) {
		if (request != null) {
			ConversationID conversationID = (ConversationID) request.getHeader(ConversationID.NAME);
			if (conversationID != null) {
				return conversationID.getId();
			}
		}
		return null;
	}

	public static List<MobileNo> checkAndGetRequireList(SipServletRequest request) {
		//解析XML.
		List<MobileNo> inviteList = null;
		boolean hasList = true;
		// 如果携带列表, 则需要解析列表
		ListIterator<SIPHeader> headers = request.getHeaders(Require.NAME);
		while(headers.hasNext()) {
			SIPHeader next = headers.next();
			if (next.getValue().equals("recipient-list-invite")) {
				hasList = true;
			}
		}
//		hasList = hasRequireList((Require) request.getHeader(Require.NAME));
		if (hasList) {
			UrcsMultipartMimeContent contents = request.getMultipartMimeContent();
			if (contents != null) {
				ResourceLists resourceList = contents.getContent(ResourceLists.class);
				if (resourceList != null) {
					inviteList = new ArrayList<MobileNo>();
					for (IMPU resource : resourceList.getMembersByResourceList()) {
						inviteList.add(MobileNo.parseFrom(getMobileNo(resource.toUri())));
					}
				}
			}
		}
		return inviteList;
	}

	public static String tryGetContactGroupPolicy(SipServletRequest request) {
		String groupplicy = "";
		if (request != null) {
			Contact contact = (Contact) request.getHeader(Contact.NAME);
			if (contact != null && contact.hasParameter(GroupConstants.CONTACT_GROUP_POLICY)) {
				groupplicy = contact.getParameter("+group.policy");
			}
		}
		return groupplicy;
	}


	private static int getGroupIdFromUri(String groupUri) {
		URI uri = IMPU.parse(groupUri).toUri();
		if (uri.isSipURI()) {
			String gId = ((SipURI) uri).getUser().toString();
			return Integer.parseInt(gId.substring(GroupConfiguration.INSTANCE.getGroupPrefix().length()));
		} else {
			return 0;
		}
	}

	private static String getMobileNo(URI uri) {
		if (uri == null) {
			return null;
		} else if (uri.isSipURI()) {
			return ((SipUri) uri).getUser();
		} else {
			return "+" + ((TelURI) uri).getPhoneNumber();
		}
	}
}
